package org.geektimes.projects.user.sql;


import org.geektimes.context.ComponentContext;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


/**
 * @author asus
 */
public class ComponentContextInitializerListener implements ServletContextListener {


    private ServletContext servletContext;


    @Override
    public void contextInitialized(ServletContextEvent sce) {

        this.servletContext = sce.getServletContext();
        ComponentContext componentContext = new ComponentContext();
        componentContext.init(servletContext);

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }


    protected Connection getConnection(){
        Context context = null;
        Connection connection = null;

        try {
            context = new InitialContext();
            //依赖查找
            Context envContext = (Context) context.lookup("java:comp/env");
            DataSource ds = (DataSource) envContext.lookup("jdbc/UserPlatformDB");
            connection = ds.getConnection();

        } catch (NamingException | SQLException e) {
            e.printStackTrace();
        }

        if (connection != null){
            servletContext.log("获取 JNDI 数据库连接成功！");
        }


        return connection;
    }

}
